<!-- 自定义告警配置 -->
<template>
	<div class="container">
		<!-- 搜索条件 -->
		<yd-form class="yd-form-wraper" :model="formData" :options="formOptions" @search="searchHandler">
			<template #form-btn>
				<el-button type="primary" icon="Search" @click="searchHandler">查 询</el-button>
			</template>
		</yd-form>

		<!--查询列表-->
		<YdTable
			:formData="formData"
			:tableConfig="tableConfig"
			:tableData="tableData.data"
			ref="multipleTable"
			@sizeChangeHandler="searchHandler"
			@currentChangeHandler="queryGrid"
			@sortChangeHandler="queryGrid"
			@selectionChangeHandler="handleSelectionChange"
		>
		</YdTable>

		<!-- 添加或修改参数配置对话框 -->
		<el-dialog :title="title" v-model="addDialogForm.open" width="1100px" append-to-body center @close="cancelHandle" :close-on-click-modal="false">
			<div style="height: 650px">
				<el-scrollbar style="height: 100%">
					<el-form ref="conForm" :model="form" :rules="dynamicRules" label-width="120px">
						<el-row>
							<el-col :span="12">
								<el-form-item label="告警指标:" prop="alarmIndicatorId">
									<el-select
										v-model="form.alarmIndicatorId"
										placeholder="请选择"
										value-key="id"
										@change="indicatorChangeHandle"
										:disabled="addDialogForm.alarmIndicatorIdDisabled"
										style="width: 322px"
									>
										<el-option v-for="(dict, index) in options.indicatorOptions" :key="index" :label="dict.name" :value="dict.id"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="指标对象:">
									{{ addDialogForm.indicatorObjName }}
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="12">
								<el-form-item label="告警名称:" prop="name">
									<el-input
										maxlength="50"
										v-model="form.name"
										placeholder="请输入告警名称"
										:disabled="addDialogForm.inputReadOnly"
										style="width: 322px"
									/>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="起步值:" prop="startValue">
									<el-input-number
										controls-position="right"
										:precision="0"
										v-model="form.startValue"
										style="width: 200px"
										:min="0"
										:max="2147483647"
										:disabled="addDialogForm.inputReadOnly"
									/>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="12">
								<el-form-item label="系统:" prop="systemId">
									<el-select v-model="form.systemId" placeholder="请选择" @change="systemChangeHandle" :disabled="addDialogForm.inputReadOnly">
										<el-option v-for="(dict, index) in options.systemOptions" :key="index" :label="dict.label" :value="dict.value"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="网端:" prop="segmentId">
									<el-select
										v-model="form.segmentId"
										placeholder="请选择"
										multiple
										collapse-tags
										filterable
										:disabled="addDialogForm.segmentDisabled"
										@change="segmentChangeHandle"
									>
										<el-option v-for="(dict, index) in options.segmentOptions" :key="index" :label="dict.label" :value="dict.value"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="12">
								<el-form-item label="业务:" prop="busId">
									<el-select
										v-model="form.busId"
										placeholder="请选择"
										multiple
										collapse-tags
										filterable
										:disabled="addDialogForm.busDisabled"
										@change="busChangeHandle"
										style="width: 322px"
									>
										<el-option v-for="(dict, index) in options.busOptions" :key="index" :label="dict.label" :value="dict.id"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="12">
								<el-form-item label="告警信息模板:" prop="alarmTemplateId">
									<el-select
										v-model="form.alarmTemplateId"
										placeholder="请选择"
										value-key="id"
										@change="templateChangeHandle"
										:disabled="addDialogForm.inputReadOnly"
									>
										<el-option v-for="(dict, index) in options.templateOptions" :key="index" :label="dict.label" :value="dict.value"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="24">
								<el-form-item label="">
									<el-input
										type="textarea"
										v-model="addDialogForm.templateContent"
										rows="5"
										:readonly="true"
										:disabled="addDialogForm.inputReadOnly"
									></el-input>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="12">
								<el-form-item label="告警阀值设置:" :required="true"> </el-form-item>
							</el-col>
						</el-row>

						<el-row style="padding-bottom: 0px">
							<el-col :span="4">
								<el-form-item label="告警顺序"> </el-form-item>
							</el-col>
							<el-col :span="5">
								<el-form-item label="告警级别"> </el-form-item>
							</el-col>
							<el-col :span="5">
								<el-form-item label="最小值"> </el-form-item>
							</el-col>
							<el-col :span="5">
								<el-form-item label="最大值"> </el-form-item>
							</el-col>
							<!--<el-col :span="4">
                <el-form-item label="是否失败">
                </el-form-item>
              </el-col>-->
							<el-col :span="5">
								<el-form-item label=""> </el-form-item>
							</el-col>
						</el-row>
						<el-row v-for="(item, index) in addDialogForm.thresholdArray">
							<el-col :span="4" class="advanceThresholdIndexClass">
								<el-form-item> {{ index + 1 }} </el-form-item>
							</el-col>
							<el-col :span="5" class="advanceThresholdOtherClass">
								<el-form-item>
									<el-select v-model="item.alarmLevelId" placeholder="请选择" style="width: 150px" :disabled="addDialogForm.inputReadOnly">
										<el-option v-for="(dict, index2) in options.alarmLevelOptions" :key="index2" :label="dict.label" :value="dict.value"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="5" class="advanceThresholdOtherClass">
								<el-form-item>
									<el-input-number
										controls-position="right"
										:precision="addDialogForm.precision"
										v-model="item.minValue"
										style="width: 165px"
										:min="0"
										:max="addDialogForm.max"
										:disabled="addDialogForm.inputReadOnly"
									/>
								</el-form-item>
							</el-col>
							<el-col :span="5" class="advanceThresholdOtherClass">
								<el-form-item>
									<el-input-number
										controls-position="right"
										:precision="addDialogForm.precision"
										v-model="item.maxValue"
										style="width: 165px"
										:min="0"
										:max="addDialogForm.max"
										:disabled="addDialogForm.inputReadOnly"
									/>
								</el-form-item>
							</el-col>
							<el-col :span="5" v-if="addDialogForm.showSubmit" class="advanceThresholdButtonClass">
								<el-button type="success" icon="Plus" @click="addThresholdHandle(index)"></el-button>
								<el-button type="danger" icon="Minus" @click="deleteThresholdHandle(index)"></el-button>
							</el-col>
						</el-row>
					</el-form>
				</el-scrollbar>
			</div>

			<template #footer class="dialog-footer">
				<el-button type="primary" @click="submitForm" v-if="addDialogForm.showSubmit">确 定</el-button>
				<el-button @click="cancelHandle" v-if="addDialogForm.showSubmit">取 消</el-button>
				<el-button type="primary" @click="cancelHandle" v-if="addDialogForm.showClose">关 闭</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="AdvancedAlarmConfig" lang="tsx">
import { ref, reactive, getCurrentInstance, onMounted, onActivated, toRefs, onBeforeMount } from 'vue';
import { useRoute } from 'vue-router';
import {
	queryCustomAlarmList,
	addCustomAlarm,
	editCustomAlarm,
	queryAlarmById,
	deleteAlarmByIds,
	editAlarmEnable,
} from '@/api/management/alarmManage/alarmConfig';
// import { queryCustomTemplateOptions } from '@/api/management/alarmManage/alarmTemplateConfig';
import { queryAdvancedIndicatorsList } from '@/api/management/alarmManage/alarmIndicator';
import {
	queryBusinessOptions,
	queryAppSystemOptions,
	querySegmentOptions,
	queryDictByType,
	queryCustomTemplateOptions,
} from '@/api/search/searchOptions';

import useCurrentInstance from '@/utils/useCurrentInstance';

const { proxy } = useCurrentInstance();
const route = useRoute();

const multipleTable = ref();

const statusOptions = ref([
	{ label: '是', value: 0 },
	{ label: '否', value: 1 },
]);
// 总条数
const total = ref(0);
// 表格数据
const alarmList = ref(null);
// 遮罩层
const loading = ref(true);
// 选中数组
const ids = ref<any[]>();
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
// 弹出层标题
const title = ref('');
// 是否详情对话框
const isDetail = ref(false);

// 表单实例
const conForm = ref();

// 表单参数
const data = reactive<anyObj>({
	form: {},
});
const { form } = toRefs(data);
let addDialogForm = reactive<anyObj>({
	// 是否显示弹出层
	open: false,
	indicatorObjName: null,
	//表达属性
	templateContent: null,
	//从自定义告警指标页面跳转进来的初始化指标id
	initAlarmIndicatorId: null,
	//业务网端互斥
	busDisabled: false,
	segmentDisabled: false,
	//修改的时候指标不能修改
	alarmIndicatorIdDisabled: false,
	//是否显示确认提交按钮，查看详情的时候不需要确认按钮
	showSubmit: true,
	//是否显示关闭
	showClose: false,
	//是否只读或者不可写
	inputReadOnly: false,
	indicatorData: {},
	thresholdArray: [
		{
			sortNum: null,
			alarmLevelId: null,
			minValue: 0,
			maxValue: 0,
			failFlag: null,
		},
	],
	//最大最小值保留两位小数
	precision: 2,
	//默认最大值，在指标单位为%比的时候，最大100
	max: 2147483647,
});
//下拉框选项
let options = reactive<anyObj>({
	indicatorOptions: [],
	templateOptions: [],
	typeOptions: [],
	systemOptions: [],
	busOptions: [],
	segmentOptions: [],
	alarmLevelOptions: [],
	indicatorOptionsForSearch: [],
	templateOptionsForSearch: [],
});
let dynamicRules = ref<anyObj>({
	alarmIndicatorId: [{ required: true, message: '告警指标不能为空', trigger: 'change' }],
});
// 指标对象是系统类型表单校验
let systemRules: anyObj = {
	alarmIndicatorId: [{ required: true, message: '告警指标不能为空', trigger: 'change' }],
	name: [{ required: true, message: '告警名称不能为空', trigger: 'blur' }],
	alarmTemplateId: [{ required: true, message: '告警信息模板不能为空', trigger: 'change' }],
	systemId: [{ required: true, message: '系统不能为空', trigger: 'change' }],
	startValue: [{ required: true, message: '起步值不能为空', trigger: 'blur' }],
};
// 指标对象是业务类型表单校验
const busRules: anyObj = {
	alarmIndicatorId: [{ required: true, message: '告警指标不能为空', trigger: 'change' }],
	name: [{ required: true, message: '告警名称不能为空', trigger: 'blur' }],
	alarmTemplateId: [{ required: true, message: '告警信息模板不能为空', trigger: 'change' }],
	systemId: [{ required: true, message: '系统不能为空', trigger: 'change' }],
	startValue: [{ required: true, message: '起步值不能为空', trigger: 'blur' }],
	busId: [{ required: true, message: '业务不能为空', trigger: 'change' }],
};
// 指标对象是网端类型表单校验
const segmentRules: anyObj = {
	alarmIndicatorId: [{ required: true, message: '告警指标不能为空', trigger: 'change' }],
	name: [{ required: true, message: '告警名称不能为空', trigger: 'blur' }],
	alarmTemplateId: [{ required: true, message: '告警信息模板不能为空', trigger: 'change' }],
	systemId: [{ required: true, message: '系统不能为空', trigger: 'change' }],
	startValue: [{ required: true, message: '起步值不能为空', trigger: 'blur' }],
	segmentId: [{ required: true, message: '网端不能为空', trigger: 'change' }],
};
// 搜索表单数据
let formData = reactive<FormModelType>({
	alarmIndicatorIds: [],
	pageNum: 1,
	pageSize: 10,
	type: 2,
});

// 表单项配置
const formOptions = ref<FormOptionType>([
	{
		type: 'select',
		label: '告警指标',
		prop: 'alarmIndicatorIds',
		placeholder: '请选择告警指标',
		api: {
			name: 'queryCustomIndicatorsOptions',
			params: {},
			// dataKey: 'data.records',
		},
		attrs: {
			multiple: true,
		},
	},
	{
		type: 'select',
		label: '告警模板',
		prop: 'alarmTemplateIds',
		placeholder: '请选择告警模板',
		api: {
			name: 'queryCustomTemplateOptions',
			// dataKey: 'data.records',
		},
		attrs: {
			multiple: true,
		},
	},

	{
		type: 'input',
		label: '告警名称',
		prop: 'name',
		placeholder: '请输入告警名称',
		// shortcutsKeys: ['last1h', 'today', 'lastDay'],
		// defaulShortcutsKey: 'lastlh',
	},
	{
		type: 'select',
		label: '是否启用',
		prop: 'isEnable',
		placeholder: '是否启用',
		isInitValue: false,
		span: 4,
		children: [
			{ label: '是', value: 0 },
			{ label: '否', value: 1 },
		],
	},
]);

// 列表配置
let tableConfig = reactive<TableConfigType>({
	columns: [
		{
			label: '告警名称',
			prop: 'name',
		},
		{
			label: '告警指标',
			prop: 'alarmIndicatorName',
		},
		{
			label: '告警维度',
			prop: 'objName',
		},
		{
			label: '告警模板',
			prop: 'alarmTemplateName',
		},
		{
			label: '启用状态',
			prop: 'isEnable',
			render: (row, val) => {
				if (proxy.checkPermi(['customAlarmConfig:enable'])) {
					return <el-switch v-model={row.isEnable} activeValue={0} inactiveValue={1} onChange={() => enableChangeHandle(row)}></el-switch>;
				}
				return <el-switch v-model={row.isEnable} disabled activeValue={0} inactiveValue={1}></el-switch>;
			},
		},
		{
			label: '操作',
			prop: '',
			width: 100,
			operation: [
				{
					text: '详情',
					handler: (scope) => getDetailHandle(scope.row),
				},
			],
		},
	],
	// 工具栏
	toolBar: [
		{ name: '新增', icon: 'yd-icon-plus', permi: ['customAlarmConfig:add'], handler: () => addHandle() },
		{ name: '修改', icon: 'yd-icon-edit', permi: ['customAlarmConfig:edit'], disable: 'single', handler: () => updateHandle() },
		{ name: '删除', icon: 'yd-icon-delete', permi: ['customAlarmConfig:delete'], disable: 'multiple', handler: () => deleteHandle() },
	],
	// 开启复选框
	enableSelection: true,
	// 开启分页
	pagination: {
		pageNum: 1,
	},
	// 加载层
	loading: true,
});
// 列表数据
let tableData = reactive({
	data: [],
});

onBeforeMount(() => {
	if (route.query.alarmIndicatorId) {
		formData.alarmIndicatorIds = [route.query.alarmIndicatorId];
		console.log('onBeforeMount', route.query.alarmIndicatorId);
	}
});
onMounted(() => {
	//从自定义告警指标页面跳转进来的初始化指标id

	addDialogForm.initAlarmIndicatorId = formData.alarmIndicatorIds;
	//查询模板
	queryCustomTemplateOptions({}).then((res: ApiResponse) => {
		const data = res.data;
		if (data != null) {
			for (var i = 0; i < data.length; i++) {
				options.templateOptions.push(data[i]);
			}
		}
	});
	//查询指标
	queryAdvancedIndicatorsList({ pageNum: 1, pageSize: 10000 }).then((res: ApiResponse) => {
		const data = res.data.records;
		if (data != null) {
			for (var i = 0; i < data.length; i++) {
				options.indicatorOptions.push(data[i]);
			}
		}
	});
	//查询系统
	queryAppSystemOptions().then((res: ApiResponse) => {
		const data = res.data;
		if (res.code === 0) {
			if (data instanceof Array) {
				let temp: anyObj = {};
				temp.value = '0';
				temp.label = '所有系统';
				data.forEach((item: any) => {
					if (item.value !== undefined) {
						item.value = item.value;
					}
				});
				data.unshift(temp);
				options.systemOptions = data;
			}
		}
	});
	//查询告警级别
	queryDictByType('sys_alarm_threshold_level').then((res: ApiResponse) => {
		const data = res.data;
		if (data != null) {
			for (var i = 0; i < data.length; i++) {
				const itemValue = parseInt(data[i].value);
				if (itemValue != 999) {
					let temp: anyObj = {};
					temp.value = parseInt(data[i].value);
					temp.label = data[i].label;
					options.alarmLevelOptions.push(temp);
				}
			}
		}
	});
	searchHandler();
});

// 搜索
function searchHandler() {
	tableConfig.pagination!.pageNum = 1;
	queryGrid();
}
function filterFormData(val: any) {
	let copyVal = JSON.parse(JSON.stringify(val));
	if (copyVal instanceof Array) {
		copyVal = copyVal.filter((v) => v !== null && v !== undefined && v !== '');
		return copyVal;
	}
}
// 查询列表
function queryGrid() {
	loading.value = true;
	console.log('formData', formData);
	let formDataObj = {
		...formData,
		// alarmIndicatorIds: filterFormData(formData.alarmIndicatorIds),
		// alarmTemplateIds: filterFormData(formData.alarmTemplateIds),
	};
	queryCustomAlarmList(formDataObj).then((res: ApiResponse) => {
		if (res.code !== 0) {
			proxy.$modal.msgError(res.msg);
			return;
		}
		tableConfig.loading = false;
		tableData.data = res.data.records;
		tableConfig.pagination!.total = res.data.total;
		tableData.data.forEach((item: any) => {
			if (item.isEnable === null) {
				item.isEnable = 1;
			}
		});
	});
}
// 多选框选中数据
function handleSelectionChange(selection: any) {
	ids.value = selection.map((item: any) => item.id);
	single.value = selection.length != 1;
	multiple.value = !selection.length;
}
/** 新增按钮操作 */
function addHandle() {
	reset();
	title.value = '增加自定义告警';
	addDialogForm.open = true;
	addDialogForm.alarmIndicatorIdDisabled = false;
	addDialogForm.showSubmit = true;
	addDialogForm.showClose = false;
	addDialogForm.inputReadOnly = false;
	//从自定义告警指标页面跳转进来的初始化指标id
	// if (addDialogForm.initAlarmIndicatorId != null) {
	// 	//重新赋值指标
	// 	for (let i = 0; i < options.indicatorOptions.length; i++) {
	// 		const item = options.indicatorOptions[i];
	// 		if (addDialogForm.initAlarmIndicatorId === item.id) {
	// 			form.value.alarmIndicatorId = item.id;
	// 			indicatorChangeHandle(item.id);
	// 			break;
	// 		}
	// 	}
	// }
}
/** 修改按钮操作 */
function updateHandle(row?: any) {
	reset();
	title.value = '修改自定义告警';
	addDialogForm.alarmIndicatorIdDisabled = true;
	addDialogForm.open = true;
	addDialogForm.showSubmit = true;
	addDialogForm.showClose = false;
	addDialogForm.inputReadOnly = false;
	let id: any;
	//由于ids是一个数组，这种写法id = row.id || ids; 有问题
	if (row) {
		id = row.id;
	} else if (ids && ids.value?.length) {
		id = ids.value[0];
	}
	if (id === null || id === '') {
		proxy.$modal.msgWarning('请选择要修改的自定义告警');
		return;
	}
	//由于indicatorChangeHandle(item)会触发指标对象逻辑，所以这一块的赋值放到indicatorChangeHandle(item)后面
	let busArr: any[] = [];
	let segmentArr: any[] = [];
	queryAlarmById(id).then((res: ApiResponse) => {
		const data = res.data;
		if (data instanceof Array && data.length) {
			let obj = data[0];
			form.value = obj;
			addDialogForm.indicatorObjName = obj.indicatorsObject;

			const dimensions = obj.dimensions;
			if (dimensions != null) {
				for (let i = 0; i < dimensions.length; i++) {
					const item = dimensions[i];

					if (item.type === 'SYSTEM') {
						item.dataId = item.dataId !== null ? String(item.dataId) : null;
						form.value.systemId = item.dataId;
					} else if (item.type === 'BUSINESS') {
						if (item.dataId !== null) {
							busArr.push(String(item.dataId));
						}
					} else if (item.type === 'SEGMENT') {
						if (item.dataId !== null) {
							segmentArr.push(String(item.dataId));
						}
					}
				}
			}

			//重新赋值模板
			options.templateOptions.forEach((item: any) => {
				if (obj.alarmTemplateId === item.value) {
					form.value.alarmTemplateId = item.value;
					templateChangeHandle(item.value);
				}
			});
			//重新赋值指标
			for (let i = 0; i < options.indicatorOptions.length; i++) {
				const item = options.indicatorOptions[i];
				if (obj.alarmIndicatorId === item.id) {
					form.value.alarmIndicatorId = item.id;
					indicatorChangeHandle(item.id);
					break;
				}
			}
			//由于indicatorChangeHandle(item)会触发指标对象逻辑，所以这一块的赋值放到indicatorChangeHandle(item)后面
			setTimeout(() => {
				if (busArr != null && busArr.length > 0) {
					form.value.busId = busArr;
				}

				if (segmentArr != null && segmentArr.length > 0) {
					form.value.segmentId = segmentArr;
				}
			}, 0);
			//重新初始化阀值
			const thresholds = obj.thresholds;
			if (thresholds != null) {
				addDialogForm.thresholdArray = [];
				thresholds.forEach((item: any) => {
					let obj = {
						sortNum: item.sortNum,
						alarmLevelId: item.alarmLevelId,
						minValue: item.minValue,
						maxValue: item.maxValue,
						failFlag: item.failFlag + '',
					};
					addDialogForm.thresholdArray.push(obj);
				});
			}
		}
	});
}
/** 删除按钮操作 */
function deleteHandle(row?: any) {
	if (row != null) {
		if (row.id != null) {
			ids.value = [];
			ids.value.push(row.id);
		}
	}
	if (ids.value === null) {
		proxy.$modal.msgWarning('请选择要删除的自定义告警信息。');
		return;
	}
	proxy.$modal
		.confirm('是否需要删除已经勾选的自定义告警信息?', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			cancelButtonClass: 'confirm-rigth-cancel-button',
			type: 'warning',
		})
		.then(() => {
			deleteAlarmByIds(ids.value).then((res) => {
				if (res.code === 0) {
					addDialogForm.open = false;
					proxy.$modal.msgSuccess('删除成功');
					searchHandler();
				} else {
					proxy.$modal.msgWarning(res.msg);
					return;
				}
			});
		})
		.catch(function () {
			addDialogForm.open = false;
			// proxy.$modal.msgSuccess('删除成功');
			searchHandler();
		});
}
/** 提交按钮 */
function submitForm() {
	if (addDialogForm.thresholdArray != null) {
		for (let i = 0; i < addDialogForm.thresholdArray.length; i++) {
			let item = addDialogForm.thresholdArray[i];
			item.sortNum = i + 1;
			//自定义告警都是数字类型
			item.valueType = 0;
			if (
				item.alarmLevelId === null ||
				item.alarmLevelId === '' ||
				item.minValue === null ||
				item.maxValue === null
				/*|| item.failFlag === null || item.failFlag === ""*/
			) {
				proxy.$modal.msgWarning('告警阀值所有字段必填');
				return;
			}
			if (item.minValue > item.maxValue) {
				proxy.$modal.msgWarning('告警阀值设置第' + (i + 1) + '行：最小值必须小于或者等于最大值');
				return;
			}
			//当前选择的指标信息，如果指标单位是百分比
			const data = addDialogForm.indicatorData;
			if (data != null && data.unitId === 7 && (item.minValue > 100 || item.maxValue > 100)) {
				proxy.$modal.msgWarning('告警阀值设置第' + (i + 1) + '行：最小值和最大值不能大于100');
				return;
			}
		}
	}
	conForm.value?.validate((valid: any) => {
		if (valid) {
			if (addDialogForm.indicatorData.objId === 2) {
				if (form.value.busId === null || form.value.busId === '') {
					proxy.$modal.msgWarning('业务不能为空');
					return;
				}
			} else if (addDialogForm.indicatorData.objId === 3) {
				if (form.value.segmentId === null || form.value.segmentId === '') {
					proxy.$modal.msgWarning('网端不能为空');
					return;
				}
			}
			form.value.thresholds = addDialogForm.thresholdArray;
			let dimensionsArray = [];
			if (form.value.systemId != null) {
				let diObj = {
					type: 'SYSTEM',
					dataId: form.value.systemId,
				};
				dimensionsArray.push(diObj);
			}
			if (form.value.busId != null) {
				for (let i = 0; i < form.value.busId.length; i++) {
					let diObj = {
						type: 'BUSINESS',
						dataId: form.value.busId[i],
					};
					dimensionsArray.push(diObj);
				}
			}
			if (form.value.segmentId != null) {
				for (let i = 0; i < form.value.segmentId.length; i++) {
					let diObj = {
						type: 'SEGMENT',
						dataId: form.value.segmentId[i],
					};
					dimensionsArray.push(diObj);
				}
			}
			form.value.dimensions = dimensionsArray;
			//设置自定义类型告警
			form.value.type = 2;
			if (form.value.id != undefined) {
				editCustomAlarm(form.value).then((res) => {
					if (res.code === 0) {
						addDialogForm.open = false;
						proxy.$modal.msgSuccess('修改成功');
						searchHandler();
					} else {
						proxy.$modal.msgWarning(res.msg);
						return;
					}
				});
			} else {
				addCustomAlarm(form.value).then((res) => {
					if (res.code === 0) {
						addDialogForm.open = false;
						proxy.$modal.msgSuccess('新增成功');
						searchHandler();
					} else {
						proxy.$modal.msgWarning(res.msg);
						return;
					}
				});
			}
		}
	});
}
function cancelHandle() {
	addDialogForm.open = false;
	setTimeout(() => {
		reset();
	}, 600);
}
// 表单重置
function reset() {
	form.value = {
		name: undefined,
	};
	dynamicRules.value = {
		alarmIndicatorId: [{ required: true, message: '告警指标不能为空', trigger: 'change' }],
	};
	//初始化保留2位小数
	addDialogForm.precision = 2;
	//初始化最大值
	addDialogForm.max = 2147483647;
	addDialogForm.busDisabled = false;
	addDialogForm.segmentDisabled = false;
	addDialogForm.templateContent = null;
	addDialogForm.indicatorObjName = null;
	conForm.value?.resetFields();
	let obj = {
		sortNum: null,
		alarmLevelId: null,
		minValue: null,
		maxValue: null,
		failFlag: null,
	};
	addDialogForm.thresholdArray = [];
	addDialogForm.thresholdArray.push(obj);
}
//模板下拉框改变
function templateChangeHandle(value: any) {
	const data = options.templateOptions.find((temp: any) => temp.value === value);
	if (data != null) {
		addDialogForm.templateContent = data.content;
	}
}
//指标下拉框改变
function indicatorChangeHandle(id: any) {
	const data = options.indicatorOptions.find((ind: any) => ind.id === id);
	if (data != null) {
		//设置最大最小值保留小数点
		if (data.unitId === 8) {
			addDialogForm.precision = 0;
		} else {
			addDialogForm.precision = 2;
		}
		if (data.unitId === 7) {
			addDialogForm.max = 100;
		} else {
			addDialogForm.max = 2147483647;
		}
		addDialogForm.indicatorObjName = data.indicatorsObject;
		addDialogForm.indicatorData = data;
		//1为系统，2为业务，3为网端
		if (addDialogForm.indicatorData.objId === 2) {
			addDialogForm.segmentDisabled = true;
			dynamicRules.value = busRules;
		} else if (addDialogForm.indicatorData.objId === 3) {
			addDialogForm.busDisabled = true;
			dynamicRules.value = segmentRules;
		} else {
			addDialogForm.busDisabled = true;
			addDialogForm.segmentDisabled = true;
			dynamicRules.value = systemRules;
		}
		if (form.value.systemId != null || form.value.systemId === 0) {
			//每次下拉清理验证信息
			systemChangeHandle(form.value.systemId);
		}
	}
	setTimeout(() => {
		conForm.value?.clearValidate();
	}, 0);
	if (isDetail.value) {
		// 如果是详情进来的,全部禁用
		addDialogForm.busDisabled = true;
		addDialogForm.segmentDisabled = true;
		isDetail.value = false;
	}
}
//系统下拉框改变
function systemChangeHandle(id: any) {
	if (id === null) {
		return;
	}
	if (form.value.alarmIndicatorId === null || form.value.alarmIndicatorId === '' || addDialogForm.indicatorData === null) {
		proxy.$modal.msgWarning('请先选择一个告警指标');
		form.value.alarmIndicatorId = null;
		// proxy.$forceUpdate();
		return;
	}
	options.busOptions = [];
	options.segmentOptions = [];
	//业务类型清空网端id
	form.value.segmentId = null;
	//网端类型清空业务id
	form.value.busId = null;
	addDialogForm.busDisabled = false;
	addDialogForm.segmentDisabled = false;

	console.log('addDialogForm.indicatorData', addDialogForm.indicatorData);
	//1为系统，2为业务，3为网端
	if (addDialogForm.indicatorData.objId === 2) {
		addDialogForm.segmentDisabled = true;
		//业务类型清空网端id
		form.value.segmentId = null;
		let temp: anyObj = {};
		temp.value = '0';
		temp.id = '0';
		temp.label = '所有业务';
		//根据系统查询业务
		if (id === '0') {
			options.busOptions = [temp];
			return;
		}
		queryBusinessOptions(id).then((res: ApiResponse) => {
			const data = res.data;
			if (res.code === 0 && data instanceof Array) {
				options.busOptions = data;
				data.unshift(temp);
			}
		});
	} else if (addDialogForm.indicatorData.objId === 3) {
		addDialogForm.busDisabled = true;
		//网端类型清空业务id
		form.value.busId = null;
		//根据系统查询网端
		let temp: anyObj = {};
		temp.value = '0';
		temp.label = '所有网端';
		if (id === '0') {
			options.segmentOptions = [temp];
			return;
		}

		querySegmentOptions(id).then((res: ApiResponse) => {
			const data = res.data;
			if (res.code === 0) {
				if (data instanceof Array) {
					data.forEach((item) => {
						if (item.value !== undefined) {
							item.value = item.value;
						}
					});
					data.unshift(temp);
					options.segmentOptions = data;
				}
			}
		});
	} else {
		//业务类型清空网端id
		form.value.segmentId = null;
		//网端类型清空网端id
		form.value.busId = null;
		addDialogForm.busDisabled = true;
		addDialogForm.segmentDisabled = true;
	}
}
//新增一行阀值
function addThresholdHandle(index: number) {
	let obj = {
		sortNum: null,
		alarmLevelId: null,
		minValue: 0,
		maxValue: 0,
		failFlag: null,
	};
	addDialogForm.thresholdArray.splice(index + 1, 0, obj);
}
//删除一行阀值
function deleteThresholdHandle(index: number) {
	if (addDialogForm.thresholdArray.length === 1) {
		proxy.$modal.msgWarning('告警阀值必须保留一行');
		return;
	}
	addDialogForm.thresholdArray.splice(index, 1);
}
// 禁用启用
function enableChangeHandle(row: any) {
	const data = {
		isEnable: row.isEnable,
		id: row.id,
		alarmIndicatorId: row.alarmIndicatorId,
	};
	//本来是启用状态，现在禁用
	if (row.isEnable === 1) {
		//在模版禁用时，需要查询m_alarms表里面是否有引用该模版，如果有需提示哪些告警引用到该模版，需解绑关系后才能禁用模版。
		let text = row.name;
		proxy.$modal
			.confirm('确认要禁用 ' + text + ' 吗?禁用后该告警将不再产生!', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				cancelButtonClass: 'confirm-rigth-cancel-button',
				type: 'warning',
			})
			.then(() => {
				editAlarmEnable(data).then((res) => {
					if (res.code === 0) {
						proxy.$modal.msgSuccess('禁用 ' + text + ' 成功');
					} else {
						proxy.$modal.msgWarning(res.msg);
						return;
					}
				});
			})
			.catch(function () {
				row.isEnable = row.isEnable === 0 ? 1 : 0;
			});
	} else {
		editAlarmEnable(data).then((res) => {
			if (res.code !== 0) {
				proxy.$modal.msgWarning(res.msg);
				loading.value = false;
				return;
			}
			proxy.$modal.msgSuccess('启用成功');
		});
	}
	multipleTable.value?.getTableRef().clearSelection();
	ids.value = [];
}
//业务下拉框选中处理方法
function busChangeHandle(ids: any) {
	debugger;
	if (ids !== null && ids !== '') {
		const splitArray = (ids + '').split(',');
		splitArray.forEach((item: any) => {
			if (item === '0') {
				form.value.busId = ['0'];
				return;
			}
		});
	} else {
		form.value.busId = null;
	}
}
//网端下拉框选中处理方法
function segmentChangeHandle(ids: any) {
	if (ids != null && ids != '') {
		const splitArray = (ids + '').split(',');
		splitArray.forEach((item: any) => {
			if (item === '0') {
				form.value.segmentId = ['0'];
				return;
			}
		});
	} else {
		form.value.segmentId = null;
	}
}
//显示详情
function getDetailHandle(row: any) {
	updateHandle(row);
	isDetail.value = true;
	title.value = '自定义告警配置详情';
	addDialogForm.showSubmit = false;
	addDialogForm.showClose = true;
	addDialogForm.inputReadOnly = true;
	addDialogForm.alarmIndicatorIdDisabled = true;
	addDialogForm.busDisabled = true;
	addDialogForm.segmentDisabled = true;
}
</script>

<style scoped>
.container {
	margin: 10px;
}

:deep.el-scrollbar__wrap {
	overflow-x: hidden;
}

.thresholdDivClass > ul {
	margin: 0;
	padding: 0;
}

.thresholdDivClass > ul > li {
	display: inline-block;
}
</style>

<style rel="stylesheet/scss" lang="scss">
/*阀值序号样式*/
.advanceThresholdIndexClass {
	.el-form-item__content {
		text-align: left !important;
		margin-left: 70px !important;
	}
}
/*阀值其他样式*/
.advanceThresholdOtherClass {
	.el-form-item__content {
		text-align: left !important;
		margin-left: 10px !important;
	}
}
/*阀值按钮样式*/
.advanceThresholdButtonClass {
	.el-button--mini {
		margin-top: 3px !important;
		margin-left: 10px !important;
	}
}
</style>
